<template>
  <div class="table-wrap">
    <!-- 搜索 -->
    <div class="searchBox">
      <el-input
        prefix-icon="el-icon-search"
        v-model="searchTableInfo"
        placeholder="请输入搜索内容"
        style="width: 30%"
        clearable
      ></el-input>
    </div>
    <!-- 列表 -->
    <el-table
      ref="table"
      :data="tableData.slice((currpage - 1) * pagesize, currpage * pagesize)"
      border
      style="width: 100%"
      stripe
      @selection-change="handleSelectionChange"
      @sort-change="changeSort"
      :row-key="getRowKeys"
    >
      <!-- <el-table-column
        type="selection"
        width="40"
        align="center"
        :reserve-selection="true"
        :key="Math.random()"
      ></el-table-column> -->
      <el-table-column
        label="用户名称"
        min-width="130"
        align="center"
        :key="Math.random()"
      >
        <template slot-scope="scope">{{ scope.row.user_name }}</template>
      </el-table-column>
      <el-table-column
        label="昵称"
        min-width="130"
        align="center"
        :key="Math.random()"
      >
        <template slot-scope="scope">
          {{ scope.row.nick_name }}
        </template>
      </el-table-column>
      <el-table-column
        label="手机号"
        min-width="140"
        align="center"
        :key="Math.random()"
      >
        <template slot-scope="scope">
          {{ scope.row.mobile }}
        </template>
      </el-table-column>
      <el-table-column
        label="邮箱"
        min-width="160"
        align="center"
        :key="Math.random()"
      >
        <template slot-scope="scope">{{ scope.row.email }}</template>
      </el-table-column>
      <el-table-column
        label="登录有效期"
        min-width="100"
        align="center"
        :key="Math.random()"
      >
        <template slot-scope="scope">{{
          scope.row.token_expired == 0
            ? "永不失效"
            : scope.row.token_expired + "分钟"
        }}</template>
      </el-table-column>
      <el-table-column
        class="play-box"
        label="操作"
        min-width="280"
        align="center"
        :key="Math.random()"
        v-if="permissionData.hideActionArr.length < 4"
      >
        <template slot-scope="scope">
          <block
            class="btn-block"
            v-for="(items, index) in scope.row.bizfors"
            :key="index"
          >
            <el-tooltip
              :disabled="items.biz_type == 0 && items.biz_for == 1"
              class="item"
              effect="dark"
              content="当前业务范围不允许分配设备"
              placement="left-start"
            >
              <span>
                <el-button
                  v-if="items.biz_type == 0"
                  size="small"
                  type="success"
                  @click="distributionFn(scope.$index, scope.row)"
                  :disabled="
                    (items.biz_type == 0 && items.biz_for == 0) ||
                    (items.biz_type == 0 && items.biz_for == -1)
                  "
                  v-permissions="{
                    url: ['sys/admin/device/set'],
                    index: scope.$index,
                    key: 'hideAction',
                    id: 'fenpeiadmin',
                  }"
                  >分配设备</el-button
                >
              </span>
            </el-tooltip>
          </block>
          <!-- :disabled="items.biz_type == 0 && items.biz_for == 0 ||items.biz_type == 0 && items.biz_for == -1"
 -->
          <!--  :content="items.biz_for ==0?'此时业务范围是[全部允许]，不可以分配设备':'(items.biz_for ==-1?'此时业务范围是[全部禁止]，不可以分配设备')"
 -->
          <el-button
            size="small"
            type="warning"
            :disabled="
              extra_super_admins.includes(scope.row.user_name)
                ? true
                : false
            "
            @click="modifyFn(scope.$index, scope.row)"
            v-permissions="{
              url: [
                'sys/admin/info',
                'role/list',
                'org/list',
                'sys/admin/bizfor/list',
              ],
              index: scope.$index,
              key: 'hideAction',
              id: 'xiugai',
            }"
            >修改</el-button
          >
          <el-button
            size="small"
            type="primary"
            :disabled="
              extra_super_admins.includes(scope.row.user_name)
                ? true
                : false
            "
            @click="audit(scope.$index, scope.row)"
            v-permissions="{
              url: ['sys/admin/device/list', 'sys/admin/api/set', 'api/list'],
              index: scope.$index,
              key: 'hideAction',
              id: 'shouquan',
            }"
            >授权API</el-button
          >
          <el-button
            size="small"
            type="danger"
            :disabled="
              extra_super_admins.includes(scope.row.user_name)
                ? true
                : false
            "
            @click="delRow(scope.$index, scope.row)"
            v-permissions="{
              url: ['sys/admin/delete'],
              index: scope.$index,
              key: 'hideAction',
              id: 'shanchu',
            }"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <el-pagination
      right
      background
      layout="total,prev, pager, next, sizes,jumper"
      :page-sizes="pageSizesArr"
      :page-size="pagesize"
      :total="tableData.length"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    ></el-pagination>

    <!-- 点击修改，弹出框 -->
    <AdminModify
      v-if="dialogVisible.show"
      :dialogVisible="dialogVisible"
      :user="user_name"
      @refreshTabeList="refreshTabeList"
    />
    <!-- 点击授权API，弹出框 -->
    <AdminAudit
      v-if="dialogVisibleAudit.show"
      :dialogVisibleAudit="dialogVisibleAudit"
      @check="fnCheck"
      @all="fnAll"
      @other="fnOther"
      @success="fnSuccess"
      :user_name="user_name"
      @refreshTabeList="refreshTabeList"
    />
    <!-- 点击分配设备，弹出框 -->
    <AdminDistribution
      v-if="dialogVisibleDistribution.show"
      :dialogVisibleDistribution="dialogVisibleDistribution"
      :user_name_check="user_name"
      :nick_name_check="nick_name"
      @refreshTabeList="refreshTabeList"
    />
  </div>
</template>

<script>
import { getData, postData } from "@/request/http";
import AdminModify from "./AdminModify";
import AdminAudit from "./AdminAudit";
//import AdminDistribution from "./AdminDistribution"; //分配设备left right
import AdminDistribution from "./AdminDistributeDevice";
export default {
  name: "AdminTable",
  props: {},
  components: { AdminModify, AdminAudit, AdminDistribution },
  data() {
    return {
      currpage: 1, //分页
      pagesize: globalPageSizes[0], //初始显示，一页几个
      pageSizesArr: globalPageSizes, //globalPageSizes在public--config中全局配置，每页显示个数数组
      searchTableInfo: "", //搜索条件
      getSearchInfo: [], //搜索后，过滤后的tableData数据
      tableChecked: [], // 多选
      batchDelectId: [], //批量删除id
      checkAll: false, // 是否全选状态
      //修改，弹出框
      dialogVisible: {
        show: false,
      },
      user_name: "", //打开弹窗，当前行user_name
      //授权弹窗
      dialogVisibleAudit: {
        show: false,
      },
      //弹出框
      dialogVisibleDistribution: {
        show: false,
      },
      nick_name: "",
      permissionData: {
        hideActionArr: [], // 操作按钮的隐藏
      },
      biz_for: 0, //biz_for这是指定范围，0代表全部允许，-1代表全部禁止，1代表指定范围。0和-1的时候不能有操作按钮。1的时候按钮显示
    };
  },
  computed: {
    // 根据计算属性模糊搜索
    tableData() {
      const searchTableInfo = this.searchTableInfo;
      //console.log(searchTableInfo);
      if (searchTableInfo) {
        return this.getSearchInfo.filter((item) => {
          return Object.keys(item).some((key) => {
            return (
              String(item[key]).toLowerCase().indexOf(searchTableInfo) > -1
            );
          });
        });
      }
      return this.getSearchInfo;
    },
    //刷新table
    submitData() {
      return this.$store.state.submitData;
    },
    //超级管理员，默认空是admin，在config中配置
    extra_super_admins() {
      if (
        Array.isArray(window.extra_super_admins) &&
        window.extra_super_admins.length == 0
      ) {
        window.extra_super_admins = ["admin"];
      } else if (!Array.isArray(window.extra_super_admins)) {
        window.extra_super_admins = [];
      }
      return window.extra_super_admins;
    },
  },
  watch: {
    //刷新table
    submitData(newVal, oldVal) {
      if (newVal != oldVal) {
        this.getList();
        this.currpage = 1;
      }
    },
  },
  created() {},
  mounted() {
    this.getList();
  },
  methods: {
    //获取初始列表数据
    getList() {
      postData(
        "/adminweb/sys/admin/list/ext",
        {
          page: 0,
        },
        {
          timeout: 120000,
        }
      )
        .then((res) => {
          if (res.code == 0) {
            let admins = res.datas.admins;
            this.getSearchInfo = admins;
          } else if (res.code == -56055) {
            return;
          } else {
            this.$message.error(res.code + "，" + res.msg);
          }
        })
        .catch((res) => {
          this.$message.error(res.code + "，" + res.msg);
        });
    },
    // 获取row的key值
    getRowKeys(row) {
      return row.user_name;
    },
    //点击 第几页
    handleCurrentChange(cpage) {
      this.currpage = cpage;
    },
    //每页有几条
    handleSizeChange(psize) {
      this.pagesize = psize;
    },
    //操作多选
    handleSelectionChange(val) {
      var that = this;
      this.batchDelectId = [];
      that.tableChecked = val;
      //console.log(that.tableChecked);
      if (val.length > 0) {
        for (let i = 0; i < val.length; i++) {
          this.batchDelectId.push(val[i]["user_name"]);
        }
      }
    },
    //排序
    changeSort(val) {
      // console.log(val);
    },
    refreshTabeList() {
      this.getList();
      this.$set(this.dialogVisible, "show", false);
      this.$set(this.dialogVisibleAudit, "show", false);
      this.$set(this.dialogVisibleDistribution, "show", false);
    },
    //删除单行
    delRow(index, rows) {
      //让接口改成数组
      // var subArr = [];
      // subArr.push(rows.user_name);
      var that = this;
      that
        .$confirm("此操作将删除:" + rows.user_name + ", 是否继续?", "删除", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
          postData("/adminweb/sys/admin/delete", {
            user_wanted: rows.user_name,
          })
            .then((res) => {
              that.logining = false;
              //  console.log(res);
              if (res.code == "0") {
                that.$message.success("删除成功");
                that.getList();
              } else {
                that.$message.error(res.code + ":" + res.msg);
              }
            })
            .catch((res) => {
              that.$message.error(res);
            });
        })
        .catch((res) => {
          that.$message.success("已取消");
        });
    },
    //点击修改按钮，弹窗
    modifyFn(index, row) {
      this.$set(this.dialogVisible, "show", true);
      // this.dialogVisible = { show: true };
      this.user_name = row.user_name;
    },
    //点击授权弹窗
    audit(index, row) {
      this.$set(this.dialogVisibleAudit, "show", true);
      // this.dialogVisibleAudit = { show: true };
      this.user_name = row.user_name;
    },
    //修改弹窗，选单个
    fnCheck(val) {
      // console.log(val);
    },
    //修改弹窗，全选
    fnAll(val) {
      //  console.log(val);
    },
    //修改弹窗，反选
    fnOther(val) {
      // console.log(val);
    },
    // 授权成功，关闭弹窗
    fnSuccess() {
      this.dialogVisibleAudit = {
        show: false,
      };
    },
    //点击分配设备，弹窗
    distributionFn(index, row) {
      this.user_name = row.user_name;
      this.nick_name = row.nick_name;

      // console.log(row.bizfors);
      let bizfors = row.bizfors;
      for (var i = 0; i < bizfors.length; i++) {
        if (bizfors[i].biz_type == 0) {
          if (bizfors[i].biz_for == 0) {
            console.log("全部允许");
            this.biz_for = 0;
            return false;
            // this.$message.error("此时业务范围是[全部允许]，不可以分配设备");
          } else if (bizfors[i].biz_for == 1) {
            console.log("指定范围");
            this.biz_for = 1;
            this.$set(this.dialogVisibleDistribution, "show", true);
          } else if (bizfors[i].biz_for == -1) {
            console.log("全部禁止");
            this.biz_for = -1;
            return false;
            // this.$message.error("此时业务范围是[全部禁止]，不可以分配设备");
          }
        }
      }
    },
  },
};
</script>
<style scoped>
/* 更改table,表头背景 */
.table-wrap >>> .el-table--border th,
.el-table__fixed-right-patch {
  /* background: #c0dee2; */
  background: #f0f3f4;
}
.table-wrap {
  margin-top: 20px;
  padding: 15px;
  overflow: hidden;
}
.searchBox {
  margin-bottom: 20px;
}
.table-wrap >>> .el-pagination {
  float: right;
  margin-top: 30px;
}

.batch-btn-con {
  margin-top: 70px;
}
.table-wrap >>> .tips {
  margin-top: 10px;
  display: block;
  font-size: 15px;
}
.btn-block {
  margin-right: 3px;
}
</style>
